package com.dming.auto.lib;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

/**
 * Created by DMing at 2018/3/16 0016
 */

public class DrawableXml {

    private static String resPath;

    private DrawableXml() {

    }

    private static void initFile(String module) {
        File directory = new File("");//设定为当前文件夹
        try {
            resPath = directory.getCanonicalPath() + File.separator + module + "\\" + "src\\main\\res";
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static DrawableXml init() {
        initFile("app");
        return new DrawableXml();
    }

    public static DrawableXml init(String module) {
        initFile(module);
        return new DrawableXml();
    }

    public void createSelectXML(String name, String normalDrawable, String checkDrawable) {
        String fileName = resPath + File.separator + "drawable" + File.separator + name + "_sl.xml";
        File file = new File(fileName);
        FileOutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        if (outputStream == null) {
            return;
        }
//        OutputStream outputStream = System.out;
        Document doc;
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder docBuilder = dbf.newDocumentBuilder();
            doc = docBuilder.newDocument();
            doc.setXmlStandalone(true);
            Element selector = doc.createElement("selector");
            selector.setAttribute(
                    "xmlns:android",
                    "http://schemas.android.com/apk/res/android");
            doc.appendChild(selector);

            Element itemNormal = doc.createElement("item");
            itemNormal.setAttribute("android:drawable", "@drawable/" + normalDrawable);
            selector.appendChild(itemNormal);

            Element itemCheck = doc.createElement("item");
            itemCheck.setAttribute("android:drawable", "@drawable/" + checkDrawable);
            itemNormal.setAttribute("android:state_checked", "true");
            selector.appendChild(itemCheck);

            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            StreamResult xmlResult = new StreamResult(outputStream);
            transformer.transform(new DOMSource(doc), xmlResult);

            System.out.println("SelectorXml: " + file); //生成了什么文件
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        }
    }


    public void createColorXML(int radiusDp, String bgColor, int strokeDp, String strokeColor) {
        String fileName = "bg_r" + radiusDp + bgColor + "_s" + strokeDp + strokeColor;
        fileName = fileName.replace("#", "_");
        File file = new File(resPath + File.separator + "drawable" + File.separator + fileName + ".xml");
        FileOutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        if (outputStream == null)return;
//        OutputStream outputStream = System.out;
        Document doc;
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder docBuilder = dbf.newDocumentBuilder();
            doc = docBuilder.newDocument();
            doc.setXmlStandalone(true);
            Element shape = doc.createElement("shape");
            shape.setAttribute(
                    "xmlns:android",
                    "http://schemas.android.com/apk/res/android");
            shape.setAttribute("android:shape", "rectangle");
            doc.appendChild(shape);

            if (bgColor != null) {
                Element solid = doc.createElement("solid");
                solid.setAttribute("android:color", bgColor);
                shape.appendChild(solid);
            }

            Element corners = doc.createElement("corners");
            corners.setAttribute("android:radius", radiusDp + "dp");
            shape.appendChild(corners);

            if (strokeColor != null) {
                Element stroke = doc.createElement("stroke");
                stroke.setAttribute("android:width", strokeDp + "dp");
                stroke.setAttribute("android:color", strokeColor);
                shape.appendChild(stroke);
            }

            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            StreamResult xmlResult = new StreamResult(outputStream);
            transformer.transform(new DOMSource(doc), xmlResult);

            System.out.println("ColorDrawable: " + file); //生成了什么文件
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        }
    }

    /**
     * 必须存在drawable
     */
    public void createSelectDrawable() {
        FilenameFilter filenameFilter = new FilenameFilter() {
            public boolean accept(File dir, String name) {
                return name.contains("drawable");
            }
        };
        File resFile = new File(resPath);
        File[] fileList = resFile.listFiles(filenameFilter);
        ArrayList<String> drawableList = new ArrayList<>();
        ArrayList<String> xmlList = new ArrayList<>();
        for (int i = 0; i < fileList.length; i++) {
            String[] drawables = fileList[i].list();
            for (int j = 0; j < drawables.length; j++) {
                if (drawables[j].endsWith("_sl.xml")) {
                    xmlList.add(drawables[j]);
                } else if (drawables[j].endsWith("_normal.png") ||
                        drawables[j].endsWith("_checked.png") ||
                        drawables[j].endsWith("_normal.xml") ||
                        drawables[j].endsWith("_checked.xml") ||
                        drawables[j].endsWith("_normal.jpg") ||
                        drawables[j].endsWith("_checked.jpg") ||
                        drawables[j].endsWith("_normal.jpeg") ||
                        drawables[j].endsWith("_checked.jpeg")) {
                    drawableList.add(drawables[j]);
                }
            }
        }

        for (String key : xmlList) {
            String name = key.replace("_sl.xml", "");
            Iterator<String> drawableIt = drawableList.iterator();
            while (drawableIt.hasNext()) {
                String value = drawableIt.next();
                boolean hasContains = value.startsWith(name);
                if (hasContains) {//如果有包含 再次判断预防前面相同，后面还有一部分不同
                    String str = value.replace(name, "");
                    boolean hasDone = str.startsWith("_normal") || str.startsWith("_checked");
                    if (hasDone) { //else还是不同的
                        drawableIt.remove();//去除重复的
                    }
                }
            }
        }
        Map<String, Boolean> filterMap = new HashMap<>();
        Iterator<String> drawableIt = drawableList.iterator();
        while (drawableIt.hasNext()) {
            String value = drawableIt.next();
            String name = value.substring(0, value.lastIndexOf("_"));
            if (filterMap.containsKey(name)) {
                boolean normal = value.contains("_normal");
                Boolean isNormal = filterMap.get(name);
                if (isNormal != normal) { //成对出现，可以生成了
                    String normalDrawable = name + "_normal";
                    String checkDrawable = name + "_checked";
                    createSelectXML(name, normalDrawable, checkDrawable);
                }
            } else { //不存在
                boolean normal = value.contains("_normal");
                filterMap.put(name, normal);
            }
        }
    }

}
